//
//  LoginView.m
//  BYR
//
//  Created by Bob on 15/3/15.
//  Copyright (c) 2015年 Bob. All rights reserved.
//

#import "LoginView.h"
#import "APIDomin.h"
#import "Users.h"
@interface LoginView ()
@property AFHTTPRequestOperationManager* Test;
@end

@implementation LoginView

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.userLogin becomeFirstResponder];
    [self inithttps];
    // Do any additional setup after loading the view from its nib.
}

- (void)inithttps{
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    self.Test =[AFHTTPRequestOperationManager manager];
    self.Test.securityPolicy = securityPolicy;
    self.Test.securityPolicy.allowInvalidCertificates = YES;
    self.Test.responseSerializer = [AFHTTPResponseSerializer serializer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)doneLogin:(id)sender {
    NSString *username = self.userLogin.text;
    NSString *scret    = self.userScret.text;
    if ([username hasPrefix:@" "] || [scret hasPrefix:@" "]) {
        return;
    }
    //NSString *t = Test;
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_STORE_USER_NAME];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_SCRET];
    [[NSUserDefaults standardUserDefaults] setObject:username forKey:USER_STORE_USER_NAME];
    [[NSUserDefaults standardUserDefaults] setObject:scret forKey:USER_SCRET];
    NSString *login = [NSString stringWithFormat:@"%@:%@",username,scret];
    NSString *loginApi = [NSString stringWithFormat:@"http://%@%@/user/login.json",login,nforum];
    loginApi = @"https://112.124.45.47:9912/api/city_all_info?city=北京市";
  //  loginApi = @"http://112.124.45.47:9902/public_data/province_cities?bussiness=1";
   // NSDictionary *dict1 = @{@"bussiness": @"1"};
    NSURL *url = [NSURL URLWithString:[loginApi stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    从URL获取json数据
    
    [self.Test GET:[loginApi stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSLog(@"获取到的数据为：%@",[NSString stringWithCString:[[dict description] cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = operation.responseString;
        NSData* data=[html dataUsingEncoding:NSUnicodeStringEncoding];
        NSMutableDictionary *dict=[NSJSONSerialization  JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
       // NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        if (dict.count < 4) {
           // NSArray *test = [dic objectForKey:@"provinces"];
           // NSLog(@"获取到的数据为：%@",[test[0] objectForKey:@"name"] );
            NSLog(@"%@",[NSString stringWithCString:[[dict description] cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding]);
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"登入失败" message:@"您的用户名并不存在，或者您的密码错误"delegate:nil cancelButtonTitle:@"重试" otherButtonTitles:nil, nil];
            [alertView show];
        }
        else{
            NSLog(@"获取到的数据为：%@",[dict description]);
            Users *user = [Users userWithJsonDictionary:dict];
            NSLog(@"%@",user);
        }
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发生错误！%@",error);
    }];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
}

- (IBAction)cancelLogin:(id)sender {
    self.userLogin.text = nil;
    self.userScret.text = nil;
    [self.navigationController popViewControllerAnimated:YES];
}
@end
